'use strict'
const UniID = require('uni-id-common')

exports.main = async (event, context) => {
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	
  const { uniIdToken, action, value } = body
 const uniID = UniID.createInstance({ context });

  // 鉴权
  const authResult = await uniID.checkToken(uniIdToken)
  if (authResult.code !== 0) {
    return {
      code: 403,
      msg: '身份验证失败'
    }
  }

  const uid = authResult.uid
  const db = uniCloud.database()
  const userCollection = db.collection('uni-id-users')

  const userRes = await userCollection.doc(uid).get()
  if (userRes.data.length === 0) {
    return {
      code: 404,
      msg: '用户不存在'
    }
  }

  let currentCount = userRes.data[0].remainingCancelCount || 0
  let newCount = currentCount

  switch (action) {
    case 'get':
      return {
        code: 0,
        msg: '获取成功',
        data: {
          remainingCancelCount: currentCount
        }
      }
    
    case 'decrease':
      if ( !Number.isInteger(value) || value <= 0) {
        return { code: 400, msg: 'value 必须为正整数' }
      }
      if (currentCount < value) {
        return { code: 403, msg: '剩余次数不足' }
      }
      newCount = currentCount - value
      break

    case 'increase':
      if (typeof value !== 'number' || value <= 0) {
        return { code: 400, msg: 'value 必须为正整数' }
      }
      newCount = currentCount + value
      break

    case 'set':
      if (typeof value !== 'number' || value < 0) {
        return { code: 400, msg: 'value 必须为非负整数' }
      }
      newCount = value
      break

    default:
      return { code: 400, msg: '不支持的操作类型 action' }
  }

  // 更新数据库
  await userCollection.doc(uid).update({
    remainingCancelCount: newCount
  })

  return {
    code: 0,
    msg: '操作成功',
    data: {
      remainingCancelCount: newCount
    }
  }
}
